import { useState, useEffect } from "react";
import styles from "./index.less";
import Tabbar from "@/components/Tabbar";
import api from "@/utils/api";
import Items from "./components/Items";




/*

    15655458016 李响

*/
export default function Page() {
  // 所有分类
  const [cates, setCates] = useState<Cate[]>([]);
  // 高亮分类的商品列表
  const [items, setItems] = useState<Item[]>([]);
  // 高亮分类 下标
  const [activeIndex, setActiveIndex] = useState(0);
  const getCates = () => {
    api.getCates().then((res) => {
      if (res.data.code === 0) {
        setCates(res.data.data);
      }
    });
  };
  // 请求高亮分类下的商品
  const getItems = () => {
    api
      .getItems({
        categoryId: cates[activeIndex].id,
      })
      .then((res) => {
        if (res.data.code === 0) {
          setItems(res.data.data.result);
        }
        if (res.data.code === 700) {
          setItems([])
        }
      });
  };
  // 切换高亮分类
  const switchActiveIndex = (index: number) => {
    setActiveIndex(index);
    
  };
  useEffect(() => {
    if (cates.length) {
      getItems();
    }
  }, [cates, activeIndex]);
  useEffect(() => {
    getCates();
  }, []);
  return (
    <>
      <div className={styles["cate-page"]}>
        <div className="cate-container">
          <div className="cates">
            {cates.map((cate: Cate, index: number) => (
              <div
                key={cate.id}
                onClick={
                  () => {
                    switchActiveIndex(index)
                  }
                }
                className={`cate ${activeIndex === index ? "active" : ""}`}
              >
                {cate.name}
              </div>
            ))}
          </div>
        </div>
        <div className="item-container">
          <Items items={items} />
        </div>
      </div>
      <Tabbar />
    </>
  );
}
